import React, { useEffect, useMemo, useState } from "react";
import ajax from "@/services";
import { echartTypes } from "@/config/character";
import EchartsCom from "./EchartsCom";
import createOpts from "./echartOptions";

export default function EchartType(props) {
  const { type = "1" } = props;

  const [loading, setLoading] = useState(true);
  // 全部柱状图数据
  const [data, setData] = useState([]);

  // 当前图表数据
  const echartOptions = useMemo(() => {
    // 没有设置默认选择择第一条数据
    // type 2.1 区分 2 展示不同的数据
    let findItem = data.filter((item) => item.is_default == 1)[0] || data[0];
    if (type === "2.1") {
      findItem = data[1] || data[0];
    }
    return {
      data: data,
      echartData: findItem,
      optionFn: (options) => createOpts(options, type),
    };
  }, [data, type]);

  const getData = () => {
    setLoading(true);
    let chart_type =
      echartTypes.filter((item) => item.value === type)[0]?.label || "";
    ajax
      .getFileList({ chart_type }, false)
      .then(
        (res) => {
          setData(res.data);
        },
        (err) => {
          setData([]);
        }
      )
      .finally(() => {
        setLoading(false);
      });
  };

  useEffect(() => {
    getData();
  }, [type]);

  return <EchartsCom {...echartOptions} loading={loading} />;
}
